<?php

namespace app\http\middleware;

use think\facade\Cache;

class RequestFrequency
{
    public function handle($request, \Closure $next)
    {
        $token = $request->header('Authorization');
        if ($token) {
            $path  = $request->url();
            $param = $request->post();
            foreach ($param as $key => $val) {
                if (is_array($val)) {
                    unset($param[$key]);
                }
            }
            $key = 'requestFre:' . md5($path . '-' . $token . '-' . http_build_query($param));
            if (Cache::store('redis')->has($key)) {
                return json(message('请求频繁,请稍后!', false, null, 503));
            }
            Cache::store('redis')->set($key, 1, 3);
        }

        try {
            $response = $next($request);
        } finally {
            if (isset($key)) {
                Cache::store('redis')->rm($key);
            }
        }

        return $response;
    }
}
